package com.ruoyi.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.common.collect.Sets;

import com.ruoyi.asms.controller.AsmsOwnMaintenanceDeptController;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.*;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.vo.DeptTreeSelectVo;
import com.ruoyi.common.core.domain.vo.DeptUserVo;
import com.ruoyi.common.core.utils.BusinessUtils;
import com.ruoyi.common.core.utils.SecurityUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.security.annotation.PreAuthorize;
import com.ruoyi.security.service.TokensService;
import com.ruoyi.system.domain.SysRoleDept;
import com.ruoyi.system.domain.SysUserRole;

import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.service.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.asms.service.IAsmsAssetFullInfoService;
import java.util.*;

/**
 * 部门信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends com.ruoyi.common.core.web.controller.BaseController {
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private IAsmsAssetFullInfoService assetFullInfoService;
    @Autowired
    private TokensService tokenService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISysRoleDeptService roleDeptService;
    @Autowired
    private ISysUserRoleService userRoleService;
    @Autowired
    private ReUsingService reUsingService;
    @Autowired
    private ISysGeographicalService sysGeographicalService;
 //   @Autowired
  //  private RemoteAsmsService remoteAsmsService;

    private AsmsOwnMaintenanceDeptController ownMaintenanceDeptController;

    /**
     * 获取部门列表
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "system:dept:list")
    @GetMapping("/list")
    @ApiOperation("获取部门列表")
    public com.ruoyi.common.core.web.page.TableDataInfo list(DeptTreeSelectVo vo) {
        SysDept dept = new SysDept();
        BeanUtils.copyProperties(vo, dept);
        //系统管理员查看所有部门、其他用户查看所属部门及其下级部门
        if (SysUser.isAdmin(SecurityUtils.getUserId())) {
            startPage();
            List<SysDept> depts = deptService.selectDeptList(dept);
            List<SysDept> deptTree = deptService.buildDeptTree(depts);
            return getDataTable(deptTree);
        } else {
            //只查看本部门和其子部门
            Long deptId = tokenService.getLoginUser().getDeptid();
            startPage();
            List<SysDept> deptList = deptService.getChildDept(deptId);

            if (vo.getDeptShortName() != null || vo.getDeptType() != null || vo.getLeader() != null
                    || vo.getIsFrozen() != null || vo.getIsCompany() != null) {
                List<SysDept> depts = deptService.selectDeptList(dept);
                HashSet<Long> a = new HashSet<>();
                HashSet<Long> b = new HashSet<>();
                deptList.forEach(item -> a.add(item.getDeptId()));
                depts.forEach(item -> b.add(item.getDeptId()));
                HashSet<Long> result = new HashSet<>(a);
                result.retainAll(b);
                List<SysDept> sysDepts = new ArrayList<>();
                if (result.size() > 0) {
                    sysDepts = deptService.list(new QueryWrapper<SysDept>().in(SysDept.DEPT_ID, result));
                }
                List<SysDept> deptTree = deptService.buildDeptTree(sysDepts);
                return getDataTable(deptTree);
            }
            List<SysDept> deptTree = deptService.buildDeptTree(deptList);
            return getDataTable(deptTree);
        }
    }

    @GetMapping("/getDeptList")
    public R<List<SysDept>> getDeptList() {
        List<SysDept> deptList = deptService.list();
        return R.ok(deptList);
    }

    @GetMapping("/getAllTopDeptList")
    public R<List<SysDept>> getAllTopDeptList() {
        List<SysDept> deptList = deptService.list(new QueryWrapper<SysDept>().eq(SysDept.PARENT_ID, 0).gt(SysDept.DEPT_ID, 1));
        return R.ok(deptList);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "system:dept:list")
    @GetMapping("/list/exclude/{deptId}")
    @ApiOperation("查询部门列表（排除节点）,deptId-部门ID-Long-非必填")
    public com.ruoyi.common.core.web.domain.AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        Iterator<SysDept> it = depts.iterator();
        while (it.hasNext()) {
            SysDept d = (SysDept) it.next();
            if (d.getDeptId().intValue() == deptId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + "")) {
                it.remove();
            }
        }
        return com.ruoyi.common.core.web.domain.AjaxResult.success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "system:dept:query")
    @GetMapping(value = "/{deptId}")
    @ApiOperation("根据部门编号获取详细信息,（deptId-部门ID-Long-必填）")
    public com.ruoyi.common.core.web.domain.AjaxResult getInfo(@PathVariable("deptId") Long deptId) {
        deptService.checkDeptDataScope(deptId);
        return com.ruoyi.common.core.web.domain.AjaxResult.success(deptService.selectDeptById(deptId));
    }

    /**
     * 获取部门下拉树列表,接口有问题
     */
    @GetMapping("/treeselect")
    @ApiOperation("获取部门下拉树列表")
    public com.ruoyi.common.core.web.domain.AjaxResult treeselect(DeptTreeSelectVo vo) {
        SysDept dept = new SysDept();
        BeanUtils.copyProperties(vo, dept);
        if (SysUser.isAdmin(SecurityUtils.getUserId())) {
            List<SysDept> depts = deptService.selectDeptList(dept);
            return com.ruoyi.common.core.web.domain.AjaxResult.success(deptService.buildDeptTreeSelect(depts));
        } else {
            QueryWrapper<SysDept> wrapper = new QueryWrapper<>();
            Set<Long> userOwnDeptIds = tokenService.getUserOwnDeptIds();
            if (userOwnDeptIds != null && userOwnDeptIds.size() > 0) {
                wrapper.in(SysDept.DEPT_ID, userOwnDeptIds);
            }
            List<SysDept> deptList = deptService.list(wrapper);
            return com.ruoyi.common.core.web.domain.AjaxResult.success(deptService.buildDeptTreeSelect(deptList));
        }
    }

    /**
     * 获取所有部门的下拉树列表
     */
    @GetMapping("/myDeptTreeSelect")
    @ApiOperation("获取所有部门的下拉树列表")
    public com.ruoyi.common.core.web.domain.AjaxResult myDeptTreeSelect() {
        List<SysDept> depts = deptService.list();
        return com.ruoyi.common.core.web.domain.AjaxResult.success(deptService.buildDeptTreeSelect(depts));
    }

    @GetMapping("/rTreeselect/{deptId}")
    @ApiOperation("获取部门的下级部门下拉树列表")
    public R<List<TreeSelect>> rTreeselect(@PathVariable Long deptId) {
        SysDept dept = new SysDept();
        dept.setDeptId(deptId);
        List<SysDept> depts = deptService.getChildDept(deptId);
        List<TreeSelect> treeSelects = deptService.buildDeptTreeSelect(depts);
        return R.ok(treeSelects);
    }

    @PostMapping("/rTreeselects")
    @ApiOperation("获取指定部门的下拉树列表")
    public R<List<TreeSelect>> rTreeselects(@RequestBody Set<Long> deptIds) {
        List<SysDept> list = null;
        if (deptIds.size() == 1) {
            if (deptIds.contains(-2L)) {
                list = deptService.list();
            }
        }
        if (list == null) {
            list = deptService.list(new QueryWrapper<SysDept>().in(deptIds != null && deptIds.size() > 0, SysDept.DEPT_ID, deptIds));
        }

        List<TreeSelect> treeSelects = deptService.buildDeptTreeSelect(list);
        return R.ok(treeSelects);
    }

    @GetMapping("/rTreeSelectsByMDeptIds")
    @ApiOperation("获取部门下拉树列表")
    public R<List<TreeSelect>> rTreeSelectsByMDeptIds() {
        Set<Long> userMaintenanceDeptIds = tokenService.getUserMaintenanceDeptIds();

        return rTreeselects(userMaintenanceDeptIds);
    }

    @GetMapping("/rTreeSelectsByMDeptIds1")
    @ApiOperation("获取部门下拉树列表")
    public R<List<TreeSelect>> rTreeSelectsByMDeptIds1() {
        Set<Long> userMaintenanceDeptIds = tokenService.getUserMaintenanceDeptIds();

        return rTreeselects(userMaintenanceDeptIds);
    }

    /**
     * 获取部门下拉树列表排查系统管理部门
     */
    @GetMapping("/treeSelectExcludeAdminDept")
    @ApiOperation("获取部门下拉树列表排查系统管理部门")
    public com.ruoyi.common.core.web.domain.AjaxResult treeSelectExcludeAdminDept() {
        List<SysDept> depts = deptService.list(new QueryWrapper<SysDept>()
                .ne(SysDept.DEPT_TYPE, "0")//非系统管理部门
                .ne(SysDept.IS_FROZEN, 0)//非冻结
                .ne(SysDept.IS_DELETE, 0));//非删除
        List<TreeSelect> treeSelects = deptService.buildDeptTreeSelect(depts);
        return com.ruoyi.common.core.web.domain.AjaxResult.success(treeSelects);
    }

    /**
     * 获取部门的下级部门列表
     */
    @GetMapping("/getLowerDeptList")
    @ApiOperation("获取部门的下级部门列表")
    public com.ruoyi.common.core.web.domain.AjaxResult getLowerDeptList(@ApiParam(value = "部门ID（若用户点击员工管理时则不传）")
                                       @RequestParam(value = "deptId", required = false) Long deptId) {
        //获取当前登录用户的部门ID
        if (deptId == null) {
            Long sysDeptId = tokenService.getLoginUser().getDeptid();
            SysDept dept = deptService.getOne(new QueryWrapper<SysDept>().eq(SysDept.DEPT_ID, sysDeptId), false);
            return com.ruoyi.common.core.web.domain.AjaxResult.success(dept);
        }
        List<SysDept> deptList = deptService.list(new QueryWrapper<SysDept>().eq(SysDept.PARENT_ID, deptId));
        return com.ruoyi.common.core.web.domain.AjaxResult.success(deptList);
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    @ApiOperation("加载对应角色部门列表树, (roleId-角色ID-Long-必填)")
    public com.ruoyi.common.core.web.domain.AjaxResult roleDeptTreeselect(@PathVariable("roleId") Long roleId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        com.ruoyi.common.core.web.domain.AjaxResult ajax = com.ruoyi.common.core.web.domain.AjaxResult.success();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("data", deptService.buildDeptTreeSelect(depts));
        return ajax;
    }

    /**
     * 新增同级部门
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "system:dept:add")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping("/addSibling")
    @ApiOperation("新增同级部门")
    @Transactional
    public com.ruoyi.common.core.web.domain.AjaxResult addSibling(@Validated @RequestBody DeptAddVo vo) {
        SysDept dept = new SysDept();
        BeanUtils.copyProperties(vo, dept);
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptFullNameUnique(dept))) {
            return com.ruoyi.common.core.web.domain.AjaxResult.error("新增部门'" + dept.getDeptFullName() + "'失败，部门名称已存在");
        }
        SysDept sysDept = deptService.selectDeptById(vo.getDeptId());
        if (sysDept != null) {
            //点击表格中的新增同级
            dept.setParentId(sysDept.getParentId());
            dept.setAncestors(sysDept.getAncestors());
            //获取上级部门用于确定部门全称
            SysDept parentDept = deptService.getOne(new QueryWrapper<SysDept>()
                    .eq(SysDept.DEPT_ID, sysDept.getParentId()));
            if (parentDept != null) {
                dept.setDeptFullName(parentDept.getDeptFullName() + vo.getDeptShortName());
                dept.setDeptType(parentDept.getDeptType());
            } else {
                dept.setDeptFullName(vo.getDeptShortName());
            }
        } else {
            //点击表格上方的新增
            dept.setParentId(0L);
            dept.setAncestors("0");
            dept.setDeptFullName(dept.getDeptShortName());
        }

        dept.setCreateBy(SecurityUtils.getUsername());
        dept.setCreateTime(System.currentTimeMillis());
        dept.setDeptId(null);
        deptService.save(dept);

        //新增部门后向角色表加入部门对应的角色数据
        String[] deptTypes = dept.getDeptType().split(",");
        deptService.addRoleInfo(deptTypes, dept.getDeptId());
        //throw new GlobalException("测试回滚");
        return com.ruoyi.common.core.web.domain.AjaxResult.success(dept.getDeptId());
    }

    /**
     * 新增下级部门
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "system:dept:add")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping("/addLower")
    @ApiOperation("新增下级部门")
    @Transactional
    public com.ruoyi.common.core.web.domain.AjaxResult addLower(@Validated @RequestBody DeptAddVo vo) {
        SysDept dept = new SysDept();
        BeanUtils.copyProperties(vo, dept);
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptFullNameUnique(dept))) {
            return com.ruoyi.common.core.web.domain.AjaxResult.error("新增部门'" + dept.getDeptFullName() + "'失败，部门名称已存在");
        }
        //获取上级部门
        SysDept info = deptService.getOne(new QueryWrapper<SysDept>()
                .eq(SysDept.DEPT_ID, dept.getParentId()));
        // 如果父节点不为正常状态,则不允许新增子节点
        if (UserConstants.DEPT_DISABLE.equals(info.getIsFrozen().toString())) {
            throw new com.ruoyi.common.core.exception.ServiceException("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        dept.setDeptFullName(info.getDeptFullName() + dept.getDeptShortName());
        dept.setDeptType(info.getDeptType());
        dept.setCreateBy(SecurityUtils.getUsername());
        dept.setCreateTime(System.currentTimeMillis());
        deptService.save(dept);

        //新增部门后向角色表加入部门对应的角色数据
        String[] deptTypes = dept.getDeptType().split(",");
        deptService.addRoleInfo(deptTypes, dept.getDeptId());
        return com.ruoyi.common.core.web.domain.AjaxResult.success();
    }

    /**
     * 新增维护方和所有方部门
     *
     * @return
     */
    @PreAuthorize
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @Transactional
    public R<SysDept> add(@RequestBody SysDept dept) {
        SysDept sysDept = new SysDept();
        BeanUtils.copyProperties(dept, sysDept);
        sysDept.setParentId(0L);
        sysDept.setAncestors("0");
        sysDept.setDeptFullName(dept.getDeptShortName());
        sysDept.setCreateBy(SecurityUtils.getUsername());
        sysDept.setCreateTime(System.currentTimeMillis());
        deptService.save(sysDept);

        //新增部门后向角色表加入部门对应的角色数据
        String[] deptTypes = dept.getDeptType().split(",");
        deptService.addRoleInfo(deptTypes, sysDept.getDeptId());
        return R.ok(sysDept);
    }

    /**
     * 修改维护方和所有方部门
     *
     * @return
     */
    @PreAuthorize
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping("/edit")
    public R<SysDept> edit(@RequestBody SysDept dept) {
        SysDept sysDept = new SysDept();
        BeanUtils.copyProperties(dept, sysDept);
        sysDept.setUpdateBy(SecurityUtils.getUsername());
        sysDept.setUpdateTime(System.currentTimeMillis());
        deptService.updateById(sysDept);
        return R.ok(sysDept);
    }

    /**
     * 修改部门
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "system:dept:edit")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改部门")
    //  @D@S("master")
    public com.ruoyi.common.core.web.domain.AjaxResult edit(@Validated @RequestBody DeptEditVo vo) {
        //获取修改之前的部门类型集合
        SysDept sysDept = deptService.getOne(new QueryWrapper<SysDept>().eq(SysDept.DEPT_ID, vo.getDeptId()));
        String[] types = sysDept.getDeptType().split(",");
        HashSet<String> beforeTypeSet = Sets.newHashSet(types);

        SysDept dept = new SysDept();
        BeanUtils.copyProperties(vo, dept);
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptFullNameUnique(dept))) {
            return com.ruoyi.common.core.web.domain.AjaxResult.error("修改部门'" + dept.getDeptFullName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(dept.getDeptId())) {
            return com.ruoyi.common.core.web.domain.AjaxResult.error("修改部门'" + dept.getDeptFullName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getIsFrozen().toString())
                && deptService.selectNormalChildrenDeptById(dept.getDeptId()) > 0) {
            return com.ruoyi.common.core.web.domain.AjaxResult.error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(SecurityUtils.getUsername());
        deptService.updateDept(dept);

        //新增类型的集合
        HashSet<String> addSet = new HashSet<>();
        //删除类型的集合
        HashSet<String> delSet = new HashSet<>();

        if (vo.getDeptType() != null && ! vo.getDeptType().equals("")) {
            //修改部门的类型后角色表、角色部门表、用户角色表需要更新
            String[] deptTypes = vo.getDeptType().split(",");
            //获取修改后的部门类型集合
            HashSet<String> afterTypeSet = Sets.newHashSet(deptTypes);
            for (String a : afterTypeSet) {
                if (!beforeTypeSet.contains(a)) {
                    addSet.add(a);
                }
            }
            for (String b : beforeTypeSet) {
                if (!afterTypeSet.contains(b)) {
                    delSet.add(b);
                }
            }
        }
        //添加记录
        if (!addSet.isEmpty()) {
            deptService.addRoleInfo(addSet.toArray(new String[0]), vo.getDeptId());
        }
        //删除记录
        if (!delSet.isEmpty()) {
            //获取需要删除的角色id集合
            HashSet<Long> delRoleIds = new HashSet<>();
            List<SysRole> roleList = roleService.list(new QueryWrapper<SysRole>()
                    .eq(SysRole.DEPT_ID, vo.getDeptId()).in(SysRole.ROLE_TYPE, delSet));
            if (roleList.size() > 0) {
                roleList.forEach(item -> delRoleIds.add(item.getRoleId()));
                roleService.removeByIds(delRoleIds);
                roleDeptService.remove(new QueryWrapper<SysRoleDept>().in(SysRoleDept.ROLE_ID, delRoleIds));
                userRoleService.remove(new QueryWrapper<SysUserRole>().in(SysUserRole.ROLE_ID, delRoleIds));
            }
        }
        //修改资产视图表中的部门
        UpdateWrapper<AsmsAssetFullInfo> updateWrapper = new UpdateWrapper<AsmsAssetFullInfo>()
                .set(AsmsAssetFullInfo.M_PARENT_ID, vo.getParentId())
                .set(AsmsAssetFullInfo.M_ANCESTORS, dept.getAncestors())
                .set(AsmsAssetFullInfo.M_DEPT_SHORT_NAME, vo.getDeptShortName())
                .set(AsmsAssetFullInfo.M_DEPT_FULL_NAME, dept.getDeptFullName())
                .set(AsmsAssetFullInfo.M_LEADER, vo.getLeader())
                .set(AsmsAssetFullInfo.M_PHONE, vo.getPhone())
                .set(AsmsAssetFullInfo.M_EMAIL, vo.getEmail())
                .eq(AsmsAssetFullInfo.MAINTENANCE_DEPT_ID, vo.getDeptId());
        reUsingService.updateFullInfo(updateWrapper);
        UpdateWrapper<AsmsAssetFullInfo> updateWrapper1 = new UpdateWrapper<AsmsAssetFullInfo>()
                .set(AsmsAssetFullInfo.U_PARENT_ID, vo.getParentId())
                .set(AsmsAssetFullInfo.U_ANCESTORS, dept.getAncestors())
                .set(AsmsAssetFullInfo.U_DEPT_SHORT_NAME, vo.getDeptShortName())
                .set(AsmsAssetFullInfo.U_DEPT_FULL_NAME, dept.getDeptFullName())
                .set(AsmsAssetFullInfo.U_LEADER, vo.getLeader())
                .set(AsmsAssetFullInfo.U_PHONE, vo.getPhone())
                .set(AsmsAssetFullInfo.U_EMAIL, vo.getEmail())
                .eq(AsmsAssetFullInfo.USE_DEPT_ID, vo.getDeptId());
        reUsingService.updateFullInfo(updateWrapper1);
        //throw new GlobalException("尝试回滚");
        return com.ruoyi.common.core.web.domain.AjaxResult.success("修改成功！");
    }

    /**
     * 删除部门
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "system:dept:remove")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    @ApiOperation("删除部门,（deptId-部门ID-Long-必填）")
    public com.ruoyi.common.core.web.domain.AjaxResult remove(@PathVariable Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return com.ruoyi.common.core.web.domain.AjaxResult.error("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return com.ruoyi.common.core.web.domain.AjaxResult.error("部门存在用户,不允许删除");
        }
        return toAjax(deptService.deleteDeptById(deptId));
    }


    /**
     * 根据部门id获取到所有子部门
     *
     * @param deptId
     * @return
     */
    @GetMapping("/getChildDept/{deptId}")
    public R<List<SysDept>> getChildDept(@PathVariable("deptId") Long deptId) {

        if (deptId != null) {
            return R.ok(deptService.getChildDept(deptId));
        } else {
            return R.fail("部门号码为空");
        }

    }

    /**
     * 批量获取部门名称
     *
     * @param deptIds
     * @return
     */
    @PostMapping("/getDeptNameByIds")
    public R<Map> getDeptNameByIds(@RequestBody List<Long> deptIds) {
        System.out.println(deptIds);
        return R.ok(deptService.getDeptNameByIds(deptIds));
    }

    /**
     * 获取上级部门
     *
     * @param deptId
     * @return
     */
    @GetMapping("/getFatherDeptById")
    public R<SysDept> getFatherDeptById(@RequestParam("deptId") Long deptId) {

        return R.ok(deptService.selectDeptById(deptId));

    }

    /**
     * 获取上级部门
     *
     * @param deptId
     * @return
     */
    @GetMapping("/getBrotherDeptById")
    public R<SysDept> getBrotherDeptById(@RequestParam("deptId") Long deptId) {

        return R.ok(deptService.selectDeptById(deptId));

    }

    @GetMapping("/getDeptById")
    public R<SysDept> getDeptById(@RequestParam("deptId") Long deptId) {

        return R.ok(deptService.selectDeptById(deptId));

    }

    @PostMapping("/getDeptManegerByDeptIds")
    public R<Map<Long, SysDept>> getDeptNameAndManegerByDeptIds(@RequestBody List<Long> deptIds) {
        List<SysDept> deptList = deptService.list(new QueryWrapper<SysDept>().
                in(deptIds.size() > 0, SysDept.DEPT_ID, deptIds));

        HashMap<Long, SysDept> rMap = new HashMap<>(deptList.size());
        for (SysDept dept : deptList) {
            List<SysUser> deptManegers = userService.getDeptManegerByDeptId(dept.getDeptId());
            if (deptManegers != null && deptManegers.size() > 0) {
                dept.setLeader(deptManegers.get(0).getNickName());
                dept.setPhone(deptManegers.get(0).getPhonenumber());
            }
            rMap.put(dept.getDeptId(), dept);
        }
        return R.ok(rMap);
    }

    @PostMapping("/deptCheckByDeptNamesAndLoginUserDeptId")
    public R<Map<String, Object>> deptCheckByDeptNamesAndLoginUserDeptId(@RequestBody List<DeptUserVo> deptUserVos) {

        Set<String> mDeptNames = new HashSet<>();
        Set<Long> deptIds = tokenService.getLoginUser().getDeptIds();
        Map<String, Object> resultMap = new HashMap<>();
        boolean isOk = true;
        Set<String> deptInfo1 = new HashSet<>();
        Set<String> oDeptNames = new HashSet<>();
        for (DeptUserVo deptUserVo : deptUserVos) {
            oDeptNames.add(deptUserVo.getODeptName());
        }
        Map<String, SysDept> oDeptNameDeptMap = new HashMap<>();
        List<SysDept> list = deptService.list(new QueryWrapper<SysDept>().in(SysDept.DEPT_SHORT_NAME, oDeptNames));
        list.forEach(item -> oDeptNameDeptMap.put(item.getDeptShortName(), item));
        for (DeptUserVo deptUserVo : deptUserVos) {
            StringBuilder stringBuilder = new StringBuilder();
            mDeptNames.add(deptUserVo.getMDeptName());
            //.in(SysDept.DEPT_ID, deptIds)
            SysDept oDept = oDeptNameDeptMap.get(deptUserVo.getODeptName());
            if (oDept == null) {
                stringBuilder.append("资产所属部门：");
                stringBuilder.append(deptUserVo.getODeptName());
                stringBuilder.append("不存在或你没有权限添加该部门的资产数据，请添加或联系管理员！");
                stringBuilder.append("\n");
                isOk = false;
            } else {
                //查看资产所属部门下的使用部门，可是是资产所属部门本身
//                SysDept uDept = deptService.getOne(new QueryWrapper<SysDept>().eq(SysDept.DEPT_SHORT_NAME, deptUserVo.getUDeptName())
//                        .like(SysDept.ANCESTORS, "," + oDept.getDeptId() + ",").or()
//                        .likeLeft(SysDept.ANCESTORS, "," + oDept.getDeptId()).or()
//                        .likeRight(SysDept.ANCESTORS, oDept.getDeptId() + ",")
//                        .or()
//                        .eq(SysDept.DEPT_ID, oDept.getDeptId())
//                , false);
                SysDept uDept = oDeptNameDeptMap.get(deptUserVo.getODeptName());
                if (uDept == null) {
                    stringBuilder.append("资产所属部门：");
                    stringBuilder.append(deptUserVo.getODeptName());
                    stringBuilder.append("下的资产使用部门：");
                    stringBuilder.append(deptUserVo.getUDeptName());
                    stringBuilder.append("不存在，请添加！");
                    stringBuilder.append("\n");
                    isOk = false;
                } else {
                    resultMap.put(oDept.getDeptShortName(), oDept);
                    resultMap.put(oDept.getDeptShortName(), uDept);
                }
            }
            deptInfo1.add(stringBuilder.toString());
        }
        List<SysDept> mDept = deptService.list(new QueryWrapper<SysDept>().in(mDeptNames.size() > 0, SysDept.DEPT_SHORT_NAME, mDeptNames));
        Set<String> mDeptNamesExit = new HashSet<>();
        mDept.forEach(item -> mDeptNamesExit.add(item.getDeptShortName()));
        mDeptNames.removeAll(mDeptNamesExit);
        Set<String> deptInfo2 = new HashSet<>();
        deptInfo2.add("");
        if (mDeptNames.size() > 0) {
            isOk = false;
            for (String mDeptName : mDeptNames) {
                String string = "资产维护方：" +
                        mDeptName +
                        "不存在，请添加！" +
                        "\n";
                deptInfo2.add(string);
            }
        } else {
            mDept.forEach(item -> resultMap.put(item.getDeptShortName(), item));
        }
        return isOk ? R.ok(resultMap) : R.fail(String.join("\n", deptInfo1) + "\n" + String.join("\n", deptInfo2));
    }

    @PostMapping("/getDeptListByIds")
    public R<List<SysDept>> getDeptListByIds(@RequestBody HashSet<Long> deptIds) {
        QueryWrapper<SysDept> wrapper = new QueryWrapper<>();
        if (deptIds.size() != 0) {
            wrapper.in(SysDept.DEPT_ID, deptIds);
        }
        List<SysDept> deptList = deptService.list(wrapper);
        return R.ok(deptList);
    }

    @PostMapping("/getDeptMapByIds")
    public R<Map<Long, SysDept>> getDeptMapByIds(@RequestBody Set<Long> deptIds) {
        Map<Long, SysDept> resultMap = new HashMap<>();
        if (deptIds != null && deptIds.size() > 0) {
            deptService.list(new QueryWrapper<SysDept>().in(SysDept.DEPT_ID, deptIds)).forEach(item -> resultMap.put(item.getDeptId(), item));
        }
        return R.ok(resultMap);
    }

    @PreAuthorize
    @ApiOperation("获取维护部门下拉框数据")
    @GetMapping("/getMDeptTreeSelect")
    public com.ruoyi.common.core.web.domain.AjaxResult getMDeptTreeSelect() {
        Long deptId = tokenService.getLoginUser().getDeptid();
        String deptType = tokenService.getLoginUser().getSysDept().getDeptType();
        if (SysUser.isAdmin(SecurityUtils.getUserId())) {
            //管理员查看所有维护部门
            List<SysDept> sysDeptList = deptService.list(new QueryWrapper<SysDept>().like(SysDept.DEPT_TYPE, ",1,")
                    .or().likeLeft(SysDept.DEPT_TYPE, ",1").or().likeRight(SysDept.DEPT_TYPE, "1,"));
            List<TreeSelect> treeSelects = deptService.buildDeptTreeSelect(sysDeptList);
            return com.ruoyi.common.core.web.domain.AjaxResult.success(treeSelects);
        } else if (deptType.contains("1")) {
            //资产维护方查看当前部门和所有下级部门
            List<SysDept> childDept = deptService.getChildDept(deptId);
            List<TreeSelect> treeSelects = deptService.buildDeptTreeSelect(childDept);
            return com.ruoyi.common.core.web.domain.AjaxResult.success(treeSelects);
        } else {
            return com.ruoyi.common.core.web.domain.AjaxResult.success(new ArrayList<>());
        }
    }

    @PreAuthorize
    @ApiOperation("资产所有方下拉框")
    @GetMapping("/getODeptTreeSelect")
    public com.ruoyi.common.core.web.domain.AjaxResult getODeptTreeSelect() {
        return com.ruoyi.common.core.web.domain.AjaxResult.success();
    }

    @PreAuthorize
    @ApiOperation("巡检部门下拉框")
    @GetMapping("/getIDeptTreeSelect")
    public com.ruoyi.common.core.web.domain.AjaxResult getIDeptTreeSelect() {
        if (SysUser.isAdmin(SecurityUtils.getUserId())) {
            //管理员查看所有巡检部门
            List<SysDept> deptList = deptService.list(new QueryWrapper<SysDept>().like(SysDept.DEPT_TYPE, ",4,")
                    .or().likeLeft(SysDept.DEPT_TYPE, ",4").or().likeRight(SysDept.DEPT_TYPE, "4,"));
            List<TreeSelect> treeSelects = deptService.buildDeptTreeSelect(deptList);
            return com.ruoyi.common.core.web.domain.AjaxResult.success(treeSelects);
        } else {
            //巡检方查看本部门和所有下级部门
            Long deptId = tokenService.getLoginUser().getDeptid();
            List<SysDept> childDept = deptService.getChildDept(deptId);
            List<TreeSelect> treeSelects = deptService.buildDeptTreeSelect(childDept);
            return com.ruoyi.common.core.web.domain.AjaxResult.success(treeSelects);
        }
    }

    @PreAuthorize
    @ApiOperation("能看到的一级资产管理部门的下拉框")
    @GetMapping("/getMyCustomerSelect")
    public com.ruoyi.common.core.web.domain.AjaxResult getMyCustomerSelect() {
        List<KeyValueVo> list = new ArrayList<>();
        Long deptId = tokenService.getLoginUser().getDeptid();
        R<HashSet<Long>> oDeptIds = ownMaintenanceDeptController.getODeptIdsByMDeptId(deptId);
        if (oDeptIds.getCode() == R.FAIL)
            throw new com.ruoyi.common.core.exception.ServiceException(oDeptIds.getMsg());
        QueryWrapper<SysDept> wrapper = new QueryWrapper<>();
        if (oDeptIds.getData().size() > 0) {
            wrapper.in(SysDept.DEPT_ID, oDeptIds.getData());
        }
        List<SysDept> deptList = deptService.list(wrapper);
        if (deptList != null) {
            for (SysDept dept : deptList) {
                KeyValueVo vo = new KeyValueVo();
                vo.setKey(dept.getDeptId());
                vo.setValue(dept.getDeptShortName());
                list.add(vo);
            }
        }
        return com.ruoyi.common.core.web.domain.AjaxResult.success(list);
    }

    /**
     * 用于远程调用，根据部门id获取部门以及它的下一级部门，然后把这些部门
     * 放到一个列表中返回
     *
     * @param deptId
     * @return 部门列表
     */
    @GetMapping("/getDeptAndNextLevelDeptList")
    public R<List<SysDept>> getDeptAndNextLevelDeptList(@RequestParam("deptId") Long deptId) {
        List<SysDept> deptList = deptService.list(new QueryWrapper<SysDept>()
                .eq(SysDept.DEPT_ID, deptId).or().eq(SysDept.PARENT_ID, deptId));

        return R.ok(deptList);
    }

    /**
     * 用于远程调用，根据部门id获取该部门的所有下级部门
     *
     * @param deptId
     * @return 部门列表
     */
    @GetMapping("/getAllNextLevelDeptList")
    public R<List<SysDept>> getAllNextLevelDeptList(@RequestParam("deptId") Long deptId) {
        List<SysDept> deptList = deptService.list(new QueryWrapper<SysDept>()
                .like(SysDept.ANCESTORS, "," + deptId + ",").or()
                .likeLeft(SysDept.ANCESTORS, "," + deptId));
        return R.ok(deptList);
    }

    @GetMapping("/getMyAllNextLevelDeptList")
    public R<List<SysDept>> getMyAllNextLevelDeptList() {
        Long deptId = tokenService.getLoginUser().getDeptid();
        List<SysDept> deptList = deptService.list(new QueryWrapper<SysDept>()
                .like(SysDept.ANCESTORS, "," + deptId + ",").or()
                .likeLeft(SysDept.ANCESTORS, "," + deptId));
        return R.ok(deptList);
    }

    @PostMapping("/import")
    @Transactional
    public com.ruoyi.common.core.web.domain.AjaxResult importData(MultipartFile file) {
        com.ruoyi.common.core.utils.poi.ExcelUtil<ImportDeptVo> util = new com.ruoyi.common.core.utils.poi.ExcelUtil<ImportDeptVo>(ImportDeptVo.class);
        List<ImportDeptVo> list = null;
        try {
            list = util.importExcel(file.getInputStream());
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return com.ruoyi.common.core.web.domain.AjaxResult.error("解析Excel出现错误，请确定数据是否为空并是否按照要求填写！");
        }
        for (ImportDeptVo importDeptVo : list) {
            if (StringUtils.isEmpty(importDeptVo.getDeptShortName1())) {
                return com.ruoyi.common.core.web.domain.AjaxResult.error("一级部门不可为空，请填写！");
            }
            Long geographicalId = 0L;
            if (StringUtils.isNotEmpty(importDeptVo.getAddress1())) {
                //处理一级地址
                SysGeographical geographical1 = sysGeographicalService.getOne(new QueryWrapper<SysGeographical>().eq(SysGeographical.PARENT_ID, 0).eq(SysGeographical.GEOGRAPHICAL_NAME, importDeptVo.getAddress1()));
                if (geographical1 == null) {
                    SysGeographical geographical = new SysGeographical();
                    geographical.setGeographicalName(importDeptVo.getAddress1());
                    geographical.setGeographicalFullName(importDeptVo.getAddress1());
                    geographical.setParentId(0L);
                    geographical.setAncestors("0");
                    geographical.setGeographicalCode("");
                    sysGeographicalService.save(geographical);
                    geographical1 = geographical;

                }
                geographicalId = geographical1.getGeographicalId();
                //处理二级地址
                if (StringUtils.isNotEmpty(importDeptVo.getAddress2())) {
                    SysGeographical geographical2 = sysGeographicalService.getOne(new QueryWrapper<SysGeographical>().eq(SysGeographical.PARENT_ID, geographical1.getGeographicalId()).eq(SysGeographical.GEOGRAPHICAL_NAME, importDeptVo.getAddress2()));
                    if (geographical2 == null) {
                        SysGeographical geographical = new SysGeographical();
                        geographical.setGeographicalName(importDeptVo.getAddress2());
                        geographical.setGeographicalFullName(importDeptVo.getAddress1() + importDeptVo.getAddress2());
                        geographical.setParentId(geographical1.getGeographicalId());
                        geographical.setAncestors("0," + geographical1.getGeographicalId());
                        geographical.setGeographicalCode("");
                        sysGeographicalService.save(geographical);
                        geographical2 = geographical;

                    }
                    geographicalId = geographical2.getGeographicalId();
                    //处理三级地址
                    if (StringUtils.isNotEmpty(importDeptVo.getAddress3())) {
                        SysGeographical geographical3 = sysGeographicalService.getOne(new QueryWrapper<SysGeographical>().eq(SysGeographical.PARENT_ID, geographical2.getGeographicalId()).eq(SysGeographical.GEOGRAPHICAL_NAME, importDeptVo.getAddress3()));
                        if (geographical3 == null) {
                            SysGeographical geographical = new SysGeographical();
                            geographical.setGeographicalName(importDeptVo.getAddress3());
                            geographical.setGeographicalFullName(importDeptVo.getAddress2() + importDeptVo.getAddress3());
                            geographical.setParentId(geographical2.getGeographicalId());
                            geographical.setAncestors(geographical2.getAncestors() + "," + geographical2.getGeographicalId());
                            geographical.setGeographicalCode("");
                            sysGeographicalService.save(geographical);
                            geographical3 = geographical;
                        }
                        geographicalId = geographical3.getGeographicalId();
                    }
                }
            }
            //处理一级部门
            SysDept dept1 = deptService.getOne(new QueryWrapper<SysDept>().eq(SysDept.DEPT_SHORT_NAME, importDeptVo.getDeptShortName1()).eq(SysDept.PARENT_ID, 0L), false);
            if (dept1 == null) {
                SysDept dept = new SysDept();
                dept.setDeptShortName(importDeptVo.getDeptShortName1());
                dept.setDeptFullName(importDeptVo.getDeptShortName1());
                dept.setAncestors("0");
                dept.setParentId(0L);
                fullDeptInfo(dept, importDeptVo, geographicalId);
                dept1 = dept;
            }
            //处理二级部门
            if (StringUtils.isNotEmpty(importDeptVo.getDeptShortName2())) {
                SysDept dept2 = deptService.getOne(new QueryWrapper<SysDept>().eq(SysDept.DEPT_SHORT_NAME, importDeptVo.getDeptShortName2()).eq(SysDept.PARENT_ID, dept1.getDeptId()), false);
                if (dept2 == null) {
                    SysDept dept = new SysDept();
                    dept.setDeptShortName(importDeptVo.getDeptShortName2());
                    dept.setDeptFullName(dept1.getDeptFullName() + importDeptVo.getDeptShortName2());
                    dept.setAncestors("0," + dept1.getDeptId());
                    dept.setParentId(dept1.getDeptId());
                    fullDeptInfo(dept, importDeptVo, geographicalId);
                    dept2 = dept;
                }
                //处理三级部门
                if (StringUtils.isNotEmpty(importDeptVo.getDeptShortName3())) {
                    SysDept dept3 = deptService.getOne(new QueryWrapper<SysDept>().eq(SysDept.DEPT_SHORT_NAME, importDeptVo.getDeptShortName3()).eq(SysDept.PARENT_ID, dept2.getDeptId()), false);
                    if (dept3 == null) {
                        SysDept dept = new SysDept();
                        dept.setDeptShortName(importDeptVo.getDeptShortName3());
                        dept.setDeptFullName(dept2.getDeptFullName() + importDeptVo.getDeptShortName3());
                        dept.setAncestors(dept2.getAncestors() + "," + dept2.getDeptId());
                        dept.setParentId(dept2.getDeptId());
                        fullDeptInfo(dept, importDeptVo, geographicalId);
                        dept3 = dept;
                    }
                }
            }
        }
        return success();
    }

    private void fullDeptInfo(SysDept dept, ImportDeptVo importDeptVo, Long geographicalId) {
        dept.setDeptType("0,1,2,4");
        dept.setLeader(importDeptVo.getLeader());
        dept.setPhone(importDeptVo.getPhone());
        dept.setGeographicalId(geographicalId);
        dept.setAddress(importDeptVo.getAddressDescription());
        dept.setCreateBy(SecurityUtils.getUsername());
        dept.setCreateTime(importDeptVo.getCreateTime() != null ? importDeptVo.getCreateTime() : System.currentTimeMillis());
        dept.setUpdateBy(SecurityUtils.getUsername());
        dept.setUpdateTime(importDeptVo.getUpdateTime() != null ? importDeptVo.getUpdateTime() : System.currentTimeMillis());
        deptService.save(dept);
        deptService.addRoleInfo(new String[]{"0", "1", "2", "4"}, dept.getDeptId());
        if (StringUtils.isNotEmpty(importDeptVo.getPhone())) {
            SysUser user = userService.getOne(new QueryWrapper<SysUser>().eq(SysUser.PHONENUMBER, importDeptVo.getPhone()), false);
            if (user == null) {
                SysUser addUser = new SysUser();
                addUser.setNickName(importDeptVo.getLeader());
                addUser.setPhonenumber(importDeptVo.getPhone());
                addUser.setCreateBy(SecurityUtils.getUsername());
                addUser.setUserName(importDeptVo.getPhone());
                addUser.setDeptId(dept.getDeptId());
                addUser.setPassword(SecurityUtils.encryptPassword(importDeptVo.getPhone()));
                List<SysRole> charger = roleService.list(new QueryWrapper<SysRole>().eq(SysRole.DEPT_ID, dept.getDeptId()).like(SysRole.ROLE_KEY, "Charger"));
                addUser.setRoleIds(charger.stream().map(SysRole::getRoleId).toArray(Long[]::new));
                userService.insertUser(addUser);
            } else {
                user.setNickName(importDeptVo.getLeader());
                user.setPhonenumber(importDeptVo.getPhone());
                user.setCreateBy(SecurityUtils.getUsername());
                user.setUserName(importDeptVo.getPhone());
                user.setDeptId(dept.getDeptId());
                user.setPassword(SecurityUtils.encryptPassword(importDeptVo.getPhone()));
                List<SysRole> charger = roleService.list(new QueryWrapper<SysRole>().eq(SysRole.DEPT_ID, dept.getDeptId()).like(SysRole.ROLE_KEY, "Charger"));
                user.setRoleIds(charger.stream().map(SysRole::getRoleId).toArray(Long[]::new));
                userService.updateUser(user);
            }
        }
    }

    @PreAuthorize
    @ApiOperation("获取所有部门的下拉树结构（微信小程序报修时选择部门）")
    @GetMapping("/getWxDeptTreeSelect")
    public com.ruoyi.common.core.web.domain.AjaxResult getDeptTreeSelect() {
        //1普通用户，deptId=null.查询所有。前端控制查询
        //2部门的用户（资产所有方）
        //3部门的用户（资产维护方）
        QueryWrapper<SysDept> wrapper = new QueryWrapper<>();
        HashSet<Long> userCanLookDeptIds = new HashSet<>();
        SysDept sysDept = tokenService.getLoginUser().getSysDept();
        if (sysDept != null && sysDept.getDeptType().contains("2")) {
            //资产所有方查看自己和自己的下级部门
            R<List<SysDept>> childDept = getChildDept(sysDept.getDeptId());
            childDept.getData().forEach(item -> userCanLookDeptIds.add(item.getDeptId()));

        }
        if (sysDept != null && sysDept.getDeptType().contains("1")) {
            //资产维护方查看所有维护的客户
            R<HashSet<Long>> r = ownMaintenanceDeptController.getODeptIdsByMDeptId(sysDept.getDeptId());
            BusinessUtils.checkRemoteService(r);
            if (r.getData() != null) {
                for (Long oDeptId : r.getData()) {
                    R<List<SysDept>> childDept = getChildDept(oDeptId);
                    childDept.getData().forEach(item -> userCanLookDeptIds.add(item.getDeptId()));
                }
            }
        }
        if (userCanLookDeptIds.size() > 0) {
            wrapper.in(SysDept.DEPT_ID, userCanLookDeptIds);
        }
        List<SysDept> deptList = deptService.list(wrapper);
        deptList.forEach(dept -> dept.setFlag(dept.getDeptId() + ""));
        List<WxTreeSelect> treeSelect = deptService.buildWxDeptTreeSelect(deptList);
        return com.ruoyi.common.core.web.domain.AjaxResult.success(treeSelect);
    }

    /**
     * 获取系统所有部门
     *
     * @return 系统部门的id与部门对象的Map
     */
    @GetMapping("/getAllDeptsMap")
    public R<Map<Long, SysDept>> getAllDeptsMap() {
        HashMap<Long, SysDept> map = new HashMap<>();
        List<SysDept> list = deptService.list();
        if (list != null) {
            list.forEach(dept -> map.put(dept.getDeptId(), dept));
        }
        return R.ok(map);
    }


    /**
     * 根据部门全名获取部门信息
     *
     * @return
     */
    @GetMapping("/getDeptByFullName")
    public R<List<SysDept>> getDeptByFullName(String deptFullName) {
        List<SysDept> list = deptService.list(new QueryWrapper<SysDept>().eq(SysDept.DEPT_FULL_NAME, deptFullName));
        return R.ok(list);
    }

    /**
     * 根据部门全名获取部门信息
     *
     * @return
     */
    @GetMapping("/getDeptByFullName1")
    public R<List<SysDept>> getDeptByFullName1(@RequestParam("deptFullName") String deptFullName) {
        List<SysDept> list = deptService.list(new QueryWrapper<SysDept>().eq(SysDept.DEPT_FULL_NAME, deptFullName));
        return R.ok(list);
    }

    @ApiOperation("获取能看到的所有资产管理部门及其子部门下拉树表数据")
    @GetMapping("/getCanSeeODeptTreeSelect")
    public com.ruoyi.common.core.web.domain.AjaxResult getCanSeeODeptTreeSelect() {
        if (SysUser.isAdmin(SecurityUtils.getUserId())) {
            //管理员查看所有维护部门
            List<SysDept> sysDeptList = deptService.list(new QueryWrapper<SysDept>().like(SysDept.DEPT_TYPE, ",2,")
                    .or().likeLeft(SysDept.DEPT_TYPE, ",2").or().likeRight(SysDept.DEPT_TYPE, "2,"));
            List<TreeSelectForMiniApp> treeSelects = deptService.buildDeptTreeSelectForMiniApp(sysDeptList);
            return com.ruoyi.common.core.web.domain.AjaxResult.success(treeSelects);
        } else {
            //资产维护方查看当前部门和所有下级部门
            List<SysDept> childDept = new ArrayList<>();
            tokenService.getUserOwnDeptIds().forEach(item -> childDept.addAll(deptService.getChildDept(item)));
            List<TreeSelectForMiniApp> treeSelects = deptService.buildDeptTreeSelectForMiniApp(childDept);
            return com.ruoyi.common.core.web.domain.AjaxResult.success(treeSelects);
        }
    }

    @ApiOperation("获取能看到的所有售后管理部门及其子部门下拉树表数据")
    @GetMapping("/getCanSeeMDeptTreeSelect")
    public com.ruoyi.common.core.web.domain.AjaxResult getCanSeeMDeptTreeSelect() {
        if (SysUser.isAdmin(SecurityUtils.getUserId())) {
            //管理员查看所有维护部门
            List<SysDept> sysDeptList = deptService.list(new QueryWrapper<SysDept>().like(SysDept.DEPT_TYPE, ",1,")
                    .or().likeLeft(SysDept.DEPT_TYPE, ",1").or().likeRight(SysDept.DEPT_TYPE, "1,"));
            List<TreeSelectForMiniApp> treeSelects = deptService.buildDeptTreeSelectForMiniApp(sysDeptList);
            return com.ruoyi.common.core.web.domain.AjaxResult.success(treeSelects);
        } else {
            //资产维护方查看当前部门和所有下级部门
            List<SysDept> childDept = new ArrayList<>();
            tokenService.getUserMaintenanceDeptIds().forEach(item -> childDept.addAll(deptService.getChildDept(item)));
            List<TreeSelectForMiniApp> treeSelects = deptService.buildDeptTreeSelectForMiniApp(childDept);
            return com.ruoyi.common.core.web.domain.AjaxResult.success(treeSelects);
        }
    }

    /**
     * 处理学校数据，根据名称判断学校类型
     * 学校类型（0幼儿园 1小学 2初中 3高中 4大学）
     */
    @GetMapping("/judgeSchoolType")
    public com.ruoyi.common.core.web.domain.AjaxResult judgeSchoolType() {
        List<SysDept> sysDepts = deptService.list();
        for (SysDept sysDept : sysDepts) {
            String name = sysDept.getDeptFullName();
            if (name.contains("幼儿园") || name.contains("幼稚园")) {
                sysDept.setSchoolType(0);
            } else if (name.contains("小学")) {
                sysDept.setSchoolType(1);
            } else if ( (name.contains("大学") || name.contains("学院") )
                    && ( (!name.contains("小学")) || (!name.contains("中学")) ) ) {
                sysDept.setSchoolType(4);
            }
        }
        deptService.updateBatchById(sysDepts);
        return com.ruoyi.common.core.web.domain.AjaxResult.success();
    }
}
